package cn.tedu.baidashi.controller;

import cn.tedu.baidashi.config.AlipayConfig;
import cn.tedu.baidashi.exception.ServiceException;
import cn.tedu.baidashi.model.*;
import cn.tedu.baidashi.service.ICartService;
import cn.tedu.baidashi.service.IOrderAddressService;
import cn.tedu.baidashi.service.IOrdersService;
import cn.tedu.baidashi.utils.OrderConstant;
import cn.tedu.baidashi.vo.AddressVo;
import cn.tedu.baidashi.vo.CartVO;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2022-02-19
 */
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IOrderAddressService orderAddressService;

    /**
     * 创建订单
     * @param shippingId
     * @return
     */
    @PostMapping("/createOrder")
    public String createOrder(Integer shippingId){
        System.out.println("shippingId:"+shippingId);
        CartVO cartVO = cartService.getCart(1);
        String orderNo = ordersService.createOrder(shippingId,cartVO);
        return "confirm.html?orderNo="+orderNo;
    }

    /**
     * 获取订单详情
     * @param orderNo
     * @return
     */
    @GetMapping("/getOrderDetail")
    public Orders getOrderDetail(@Param("orderNo") Long orderNo){
        Orders order = ordersService.getOrderDetail(1,orderNo);
        return order;
    }

    /**
     * 支付
     * @param request
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @GetMapping("/pay")
    public String pay(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {
        Orders order = ordersService.getOrderDetail(1,Long.parseLong(request.getParameter("orderNo")));

        request.setCharacterEncoding("UTF-8");

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(order.getOrderNo().toString());
        //付款金额，必填
        String total_amount = new String(order.getOrderTotal().toString());
        //订单名称，必填
        String subject = new String("订单号:"+order.getOrderNo().toString());
        //商品描述，可空
        String body = "";

        System.out.println("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println(result);
        return result;
    }

    /**
     * 支付结果
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @GetMapping("/result")
    public String result(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
        }else {
            System.out.println("验签失败");
        }

        return "result.html";
    }

    @RequestMapping("/notify")
    public String notify(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            Orders order = ordersService.getOrderDetail(1,Long.parseLong(out_trade_no));

            // 验证该通知数据中的out_trade_no是否为商户系统中创建的订单号
            if(order==null){
                return "fail";
            }

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // 卖家支付宝账号
            String seller_email = new String(request.getParameter("seller_email").getBytes("ISO-8859-1"),"UTF-8");

            // 验证通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方
            if(seller_email!="conxbl4972@sandbox.com"){
                return "fail";
            }

            // 买家付款时间
            String gmt_payment = new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if (trade_status.equals("TRADE_SUCCESS")){
                //付款完成后，支付宝系统发送该交易状态通知
                //判断该笔订单是否在商户网站中已经做过处理
                //如果订单是未付款状态
                if(order.getStatus()== OrderConstant.ORDER_WAY_PAY){
                    order.setStatus(OrderConstant.ORDER_PAID);
                    order.setPaymentTime(LocalDateTime.parse(gmt_payment, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            }

            return "success";

        }else {//验证失败
            return "fail";

        }
    }

    @GetMapping("/provinces")
    public List<Province> getAllProvinces(){
        return orderAddressService.getProvinces();
    }

    @GetMapping("/{provinceName}/citys")
    public List<City> getCitysByProvinceName(@PathVariable String provinceName){
        return orderAddressService.getCitysByProvinceName(provinceName);
    }

    @GetMapping("/{cityName}/zones")
    public List<Zone> getZonesByCityName(@PathVariable String cityName){
        return orderAddressService.getZonesByCityName(cityName);
    }

    @GetMapping("/getAddresses")
    public List<Address> getAddresses(){
//        if(未登录){
//            throw new ServiceException("用户未登录");
//        }
        return orderAddressService.getAddressesByUserName("江颖");
    }

    @PostMapping("/addAddress")
    public Address addAddress(@Validated AddressVo addressVO, BindingResult result){
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        return orderAddressService.addAddress(addressVO,"username");
    }

    @PostMapping("/updateAddress")
    public Address updateAddress(Integer addressId,@Validated AddressVo addressVO, BindingResult result){
        System.out.println("addressId:"+addressId);
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        return orderAddressService.updateAddress(addressId,addressVO,"江颖");
    }
}
